package com.studyyang.workmodoul.pubsub;

import com.rabbitmq.client.*;
import com.studyyang.utils.RabbitmqUtils;
import com.studyyang.utils.constant.RabbitMqConstant;

import java.io.IOException;

/**
 * 消息订阅者：新浪
 *
 * @Author yangjin
 * @Description
 * @Date 2021/10/29/23:17
 **/
public class SubscriberXinlang {

    public static void main(String[] args) throws IOException {
        //获取mq连接
        Connection rabbitMqConn = RabbitmqUtils.getRabbitMqConn();
        //连接信道channel
        Channel channel = rabbitMqConn.createChannel();
        //声明队列
        channel.queueDeclare(RabbitMqConstant.QUEUE_WEATHER_XINLANG,false,false,false,null);
        //将声明的队列绑定到交换机上
        /**
         * queueBind(string，string，string)
         * 1、队列名称
         * 2、交换机名称
         * 3、路由配置
         */
        channel.queueBind(RabbitMqConstant.QUEUE_WEATHER_XINLANG,RabbitMqConstant.PUB_SUB_EXCHANGE_WEATHER,"");
        channel.basicQos(1);
        //创建消息消费者，进行消息消费
        channel.basicConsume(RabbitMqConstant.QUEUE_WEATHER_XINLANG,false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /*super.handleDelivery(consumerTag, envelope, properties, body);*/
                //将消息的字节数组转换为字符串
                String messageStr = new String(body);
                System.out.println("新浪-接收到的天气消息为：" + messageStr);
                //进行消息的手动确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}
